package com.library.service;

import com.library.dto.BookDTO;
import com.library.entity.Book;
import com.library.entity.Favorite;
import com.library.entity.User;
import com.library.exception.BusinessException;
import com.library.exception.NotFoundException;
import com.library.repository.BookRepository;
import com.library.repository.FavoriteRepository;
import com.library.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 收藏服务类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FavoriteService {
    private final FavoriteRepository favoriteRepository;
    private final BookRepository bookRepository;
    private final UserRepository userRepository;

    /**
     * 收藏图书
     */
    @Transactional
    public void addFavorite(Long userId, Long bookId) {
        // 检查用户是否存在
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new NotFoundException("用户不存在"));

        // 检查图书是否存在
        Book book = bookRepository.findById(bookId)
                .orElseThrow(() -> new NotFoundException("图书不存在"));

        // 检查是否已收藏
        if (favoriteRepository.existsByUserIdAndBookId(userId, bookId)) {
            throw new BusinessException("您已收藏该图书");
        }

        // 创建收藏记录
        Favorite favorite = new Favorite();
        favorite.setUser(user);
        favorite.setBook(book);
        favoriteRepository.save(favorite);
        log.info("收藏图书成功: 用户ID={}, 图书ID={}", userId, bookId);
    }

    /**
     * 取消收藏
     */
    @Transactional
    public void removeFavorite(Long userId, Long bookId) {
        Favorite favorite = favoriteRepository.findByUserIdAndBookId(userId, bookId)
                .orElseThrow(() -> new NotFoundException("收藏记录不存在"));

        // 检查权限
        if (!favorite.getUser().getId().equals(userId)) {
            throw new BusinessException("无权操作此收藏");
        }

        favoriteRepository.delete(favorite);
        log.info("取消收藏成功: 用户ID={}, 图书ID={}", userId, bookId);
    }

    /**
     * 获取收藏列表
     */
    public List<BookDTO> getFavorites(Long userId) {
        List<Favorite> favorites = favoriteRepository.findByUserIdOrderByCreatedAtDesc(userId);
        return favorites.stream()
                .map(f -> convertToDTO(f.getBook()))
                .collect(Collectors.toList());
    }

    /**
     * 检查是否已收藏
     */
    public boolean isFavorite(Long userId, Long bookId) {
        return favoriteRepository.existsByUserIdAndBookId(userId, bookId);
    }

    /**
     * 将Book实体转换为BookDTO
     */
    private BookDTO convertToDTO(Book book) {
        return new BookDTO(
                book.getId(), book.getTitle(), book.getAuthor(), book.getIsbn(),
                book.getCategory(), book.getDescription(), book.getStock(),
                book.getIsRecommended(), book.getCreatedAt());
    }
}

